import { mapGetters } from 'vuex'
import { excelJsonExport } from '@vimi/utils-tool'

export const exportExcel = async ({
  filename,
  tableColumns,
  params,
  dataAdapter,
  fetchData,
  onLoaded = () => {},
}) => {
  const exportTable = []
  tableColumns
    .filter(item => !item.operations)
    .forEach(item => {
      if (item.columns) {
        exportTable.push(...item.columns)
      } else {
        exportTable.push(item)
      }
    })
  const header = {}
  const headerCellStyles = {}
  const columns = exportTable.map((item, i) => {
    const { prop, label } = item.attrs || {}
    header[prop] = label
    headerCellStyles[`${String.fromCharCode(65 + i)}1`] = { font: { bold: true } }
    return prop
  })

  const { index, size, ...p } = params
  const [res = {}] = await fetchData(p)
  onLoaded()

  const data = (res.data || []).map(dataAdapter)

  excelJsonExport({
    columns,
    data: [header, ...data],
    filename,
    styles: {
      border: {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      },
      alignment: {
        vertical: 'center',
        horizontal: 'center',
        wrapText: true,
      },
    },
    cellStyles: {
      ...headerCellStyles,
    },
  })
}

export default {
  data() {
    return {
      loading: false,
      tableData: [],
      totalCount: 0,
      exportLoading: false,
      tableName: 'customer_related',
      dateFmt: 'yyyy-MM-dd hh:mm',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'job', 'userId', 'user']),
    manageParams() {
      const params = {}
      params['recommend_service.eq'] = this.clientId
      params['gua_type.eq'] = '4'
      return params
    },
  },
  methods: {
    getParams() {
      return {
        ...this.params,
        ...this.manageParams,
      }
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.getParams())
      this.loading = false

      const data = res.data || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.getParams(),
        dataAdapter: this.dataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
  },
}
